#include <stdio.h>
#include <winsock2.h>
#include "http/http.h"

#pragma comment(lib, "ws2_32.lib")

// 创建socket监听
SOCKET createServerSocket(const int port) {
    SOCKET ListenSocket = INVALID_SOCKET;
    // 创建监听套接字
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        printf("Error creating socket: %d\n", WSAGetLastError());
        goto onError;
    }
    // 绑定端口
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);
    if (bind(ListenSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        printf("Bind failed: %d\n", WSAGetLastError());
        goto onError;
    }
    // 监听端口
    if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
        printf("Listen failed: %d\n", WSAGetLastError());
        goto onError;
    }
    return ListenSocket;

    onError:
        if (ListenSocket != INVALID_SOCKET) closesocket(ListenSocket);
        return INVALID_SOCKET;
}

// handlers.c
void getIndex(HTTPRequest *request, HTTPResponse *response);
void getPublicResources(HTTPRequest *request, HTTPResponse *response);
void postIndex(HTTPRequest *request, HTTPResponse *response);

void main() {
    // 初始化wsa
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        printf("WSAStartup failed: %d\n", WSAGetLastError());
        return;
    }

    // 定义路由表
    Route routes[] = {
        {"GET", "/", true, getIndex},
        {"POST", "/", true, postIndex},
        {"GET", "/assets", false, getPublicResources},
    };
    constexpr size_t routeCount = sizeof(routes) / sizeof(Route);
    // 启动http服务器
    const SOCKET serverSocket = createServerSocket(8000);
    runHTTPServer(serverSocket, routes, routeCount, 8, 80);
    closesocket(serverSocket);

    // 清理wsa
    WSACleanup();
}
